<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-item label="客户编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input disabled v-decorator="['customerCode', validatorRules.customerCode]" placeholder="请输入客户编码"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['customerName', validatorRules.customerName]" placeholder="请输入客户名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="所属行业" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['customerTrade', validatorRules.customerTrade]" :trigger-change="true" dictCode="park_customer_trade" placeholder="请选择所属行业"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="跟进人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-user-by-dep :multi="false" v-decorator="['followUp', validatorRules.followUp]"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="来访项目" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['project', validatorRules.project]" :trigger-change="true" dictCode="xy_park_project,project_name,project_code" placeholder="请选择来访项目"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="首次来访日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择首次来访日期" v-decorator="['visitDate', validatorRules.visitDate]" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="客户来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['customerSource']" :trigger-change="true" dictCode="xy_park_customer_source" placeholder="请选择客户来源"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="意向等级" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['intentionLevel']" :trigger-change="true" dictCode="park_intention_level" placeholder="请选择意向等级"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="成交几率(%)" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['probability', validatorRules.probability]" placeholder="请输入成交几率" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="客户需求" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['customerDemand', validatorRules.customerDemand]" :trigger-change="true" dictCode="park_customer_demand" placeholder="请选择客户需求"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="装修需求" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['renovation', validatorRules.renovation]" :trigger-change="true" dictCode="park_renovation" placeholder="请选择装修需求"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="需求面积自" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['demandAreafrom']" placeholder="请输入需求面积自" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="需求面积到" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['demandAreato']" placeholder="请输入需求面积到" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="客户预算从(万)" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['budgetFrom']" placeholder="请输入客户预算从" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="客户预算到(万)" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['budgetTo']" placeholder="请输入客户预算到" style="width: 100%"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="客户联系人" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="xyParkCustomercontactTable.loading"
          :columns="xyParkCustomercontactTable.columns"
          :dataSource="xyParkCustomercontactTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"/>
      </a-tab-pane>
      <a-tab-pane tab="客户意向房源" :key="refKeys[1]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[1]"
          :loading="xyParkIntentionhouseTable.loading"
          :columns="xyParkIntentionhouseTable.columns"
          :dataSource="xyParkIntentionhouseTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import pick from 'lodash.pick'
import { getAction } from '@/api/manage'
import { FormTypes, getRefPromise } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import { USER_AUTH } from '@/store/mutation-types'
export default {
  name: 'XyParkCustomerForm',
  mixins: [JEditableTableMixin],
  components: {
    JFormContainer,
    JDate,
    JSelectUserByDep,
    JDictSelectTag
  },
  data() {
    function getIphoneAuth() {
      const authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')
      let flag = false
      authList.forEach(item => {
        if (item.action === 'field:this:phone') {
          flag = true
        }
      })
      return flag
    }
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        customerCode: {
          rules: [
            { required: true, message: '请输入客户编码!' },
            { validator: (rule, value, callback) => validateDuplicateValue('xy_park_customer', 'customer_code', value, this.model.id, callback) }
          ]
        },
        customerName: {
          rules: [
            { required: true, message: '请输入客户名称!' }
          ]
        },
        customerTrade: {
          rules: [
            { required: true, message: '请输入所属行业!' }
          ]
        },
        followUp: {
          rules: [
            { required: true, message: '请输入跟进人!' }
          ]
        },
        project: {
          rules: [
            { required: true, message: '请输入来访项目!' }
          ]
        },
        visitDate: {
          rules: [
            { required: true, message: '请输入首次来访日期!' }
          ]
        },
        probability: {
          rules: [
            { required: false },
            { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
          ]
        },
        customerDemand: {
          rules: [
            { required: true, message: '请输入客户需求!' }
          ]
        },
        renovation: {
          rules: [
            { required: true, message: '请输入装修需求!' }
          ]
        }
      },
      refKeys: ['xyParkCustomercontact', 'xyParkIntentionhouse'],
      tableKeys: ['xyParkCustomercontact', 'xyParkIntentionhouse'],
      activeKey: 'xyParkCustomercontact',
      // 客户联系人
      xyParkCustomercontactTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '联系人',
            key: 'contacts',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '联系电话',
            key: 'phone',
            type: getIphoneAuth() ? FormTypes.input : FormTypes.hidden,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '邮箱',
            key: 'email',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ pattern: 'e', message: '${title}格式不正确' }]
          },
          {
            title: '职务',
            key: 'position',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          }
        ]
      },
      // 客户意向房源
      xyParkIntentionhouseTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '房源号',
            key: 'houseCode',
            type: FormTypes.popup,
            popupCode: 'v_xy_park_houseing',
            destFields: 'houseCode,project,building,floor,buildingArea,propertyArea,decoration',
            orgFields: 'house_code,project,building,floor,building_area,property_area,decoration',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '所属项目',
            key: 'project',
            type: FormTypes.select,
            dictCode: 'xy_park_project,project_name,project_code',
            width: '200px',
            disabled: true,
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '所属楼宇',
            key: 'building',
            type: FormTypes.select,
            disabled: true,
            dictCode: 'xy_park_buildling,building_name,building_code',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '楼层',
            key: 'floor',
            disabled: true,
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '建筑面积（㎡）',
            key: 'buildingArea',
            disabled: true,
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '产权面积（㎡）',
            key: 'propertyArea',
            disabled: true,
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '装修情况',
            key: 'decoration',
            disabled: true,
            type: FormTypes.select,
            dictCode: 'park_renovation',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: 'house_code',
            key: 'house_code',
            type: 'hidden'
          },
          {
            title: 'building_area',
            key: 'building_area',
            type: 'hidden'
          },

          {
            title: 'property_area',
            key: 'property_area',
            type: 'hidden'
          }
        ]
      },
      url: {
        add: '/community/xyParkCustomer/add',
        edit: '/community/xyParkCustomer/edit',
        queryById: '/community/xyParkCustomer/queryById',
        xyParkCustomercontact: {
          list: '/community/xyParkCustomer/queryXyParkCustomercontactByMainId'
        },
        xyParkIntentionhouse: {
          list: '/community/xyParkCustomer/queryXyParkIntentionhouseByMainId'
        }
      }
    }
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false
    },
    // 表单模式：false流程表单 true普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  methods: {
    addBefore() {
      this.form.resetFields()
      this.xyParkCustomercontactTable.dataSource = []
      this.xyParkIntentionhouseTable.dataSource = []
    },
    getAllTable() {
      const values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      const fieldval = pick(this.model, 'customerCode', 'customerName', 'customerTrade', 'followUp', 'customerStatus', 'project', 'visitDate', 'customerSource', 'intentionLevel', 'probability', 'customerDemand', 'renovation', 'demandAreafrom', 'demandAreato', 'budgetFrom', 'budgetTo')
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.model.customerCode) {
        const params = { id: this.model.customerCode }
        this.requestSubTableData(this.url.xyParkCustomercontact.list, params, this.xyParkCustomercontactTable)
        this.requestSubTableData(this.url.xyParkIntentionhouse.list, params, this.xyParkIntentionhouseTable)
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      const main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        xyParkCustomercontactList: allValues.tablesValue[0].values,
        xyParkIntentionhouseList: allValues.tablesValue[1].values
      }
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        const params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, 'customerCode', 'customerName', 'customerTrade', 'followUp', 'customerStatus', 'project', 'visitDate', 'customerSource', 'intentionLevel', 'probability', 'customerDemand', 'renovation', 'demandAreafrom', 'demandAreato', 'budgetFrom', 'budgetTo'))
    }

  }
}
</script>

<style scoped>
</style>
